<script setup>
import { ref, defineEmits } from 'vue'
let emits = defineEmits(['upload'])
let fileBtn = ref(null)
let src = ref(undefined)
function boxClick() {
    fileBtn.value.click()
}
function getObjectURL(file) {
    let url = null;
    if (window.createObjectURL != undefined) { // basic
        url = window.createObjectURL(file);
    } else if (window.webkitURL != undefined) { // webkit or chrome
        url = window.webkitURL.createObjectURL(file);
    } else if (window.URL != undefined) { // mozilla(firefox)
        url = window.URL.createObjectURL(file);
    }
    return url;
}
function upload(event) {
    let formdata = new FormData()
    formdata.append('file', event.target.files[0])
    emits('upload',formdata);
    src.value=getObjectURL(event.target.files[0])
    // console.log(src.value);
}
</script>

<template>
    <div>
        <div class="box" @click="boxClick()">
            <img :src="src" v-if="src">
            <slot v-if="!src"></slot>
        </div>
        <input v-show="false" type="file" ref="fileBtn" @change="upload($event)">
    </div>
</template>

<style scoped>
.box {
    width: 5em;
    height: 5em;
    border: .2em solid var(--color-theme);
    border-radius: .5em;
    overflow: hidden;
    display: flex;
    justify-content: center;
    align-items: center;
    cursor: pointer;
}

img {
    width: 100%;
    height: 100%;
    object-fit: cover;
}
</style>